package designpatterns.stragetypattern;

import java.io.*;

public class StrategyOne implements EncryptStrategy{
    String password;
    public StrategyOne(){
        this.password = "I love this game.";
    }
    StrategyOne(String password) {
        if (password.length() == 0) {
            this.password = "I love this game.";
        }
        this.password = password;
    }
    @Override
    public void encryptFile(File file) {
        try {
            byte[] a = password.getBytes();
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] b = new byte[(int) file.length()];
            int m = fileInputStream.read(b);
            for (int i = 0; i < m; i++) {
                int n = b[i] + a[i % a.length];
                b[i] = (byte) n;
            }
            fileInputStream.close();
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(b, 0, m);
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String decryptFile(File file) {
        try {
            byte[] a = password.getBytes();
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] b = new byte[(int) file.length()];
            int m = fileInputStream.read(b);
            for (int i = 0; i < m; i++) {
                int n = b[i] - a[i % a.length];
                b[i] = (byte) n;
            }
            fileInputStream.close();
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(b, 0, m);
            fileOutputStream.close();
            return new String(b, 0, m);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
